package cn.yuanqiao.auth.util;

import org.apache.commons.codec.binary.Base64;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Sm4Utils {
    private String iv = "";
    private boolean hexString = false;
    private static Pattern P = Pattern.compile("\\s*|\t|\r|\n");
    public Sm4Utils()
    {
    }

    public String encryptData_ECB(String plainText,String secretKey)
    {
        //LOG.debug("进入ECB加密函数");
        //LOG.debug("加密字符串参数plainText：" + plainText);
        //LOG.debug("加密秘钥secretKey：" + secretKey);
//        System.out.println("进入ECB加密函数，加密字符串参数plainText："+plainText+",加密秘钥secretKey："+secretKey);
        try
        {
            Sm4Context ctx = new Sm4Context();
            ctx.isPadding = true;
            ctx.mode = Sm4.SM4_ENCRYPT;

            byte[] keyBytes;
            if (hexString)
            {
                keyBytes = Util.hexStringToBytes(secretKey);
            }
            else
            {
                keyBytes = secretKey.getBytes();
            }

            Sm4 sm4 = new Sm4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes("UTF-8"));
            String cipherText = Base64.encodeBase64String(encrypted);
            //String cipherText = new BASE64Encoder().encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0)
            {
                Matcher m = P.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        }
        catch (Exception e)
        {
        	System.out.println("ECB加密失败"+e);
            //LOG.debug("ECB加密失败");
            return null;
        }
    }

    public String decryptData_ECB(String cipherText,String secretKey)
    {
        //LOG.debug("进入ECB解密函数");
        //LOG.debug("解密字符串参数cipherText：" + cipherText);
        //LOG.debug("解密秘钥secretKey：" + secretKey);
//        System.out.println("进入ECB解密函数，解密字符串参数cipherText："+cipherText+",解密秘钥secretKey："+secretKey);
        try
        {
            Sm4Context ctx = new Sm4Context();
            ctx.isPadding = true;
            ctx.mode = Sm4.SM4_DECRYPT;

            byte[] keyBytes;
            if (hexString)
            {
                keyBytes = Util.hexStringToBytes(secretKey);
            }
            else
            {
                keyBytes = secretKey.getBytes();
            }

            Sm4 sm4 = new Sm4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            //byte[] decrypted = sm4.sm4_crypt_ecb(ctx, new BASE64Decoder().decodeBuffer(cipherText));
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Base64.decodeBase64(cipherText));
//            System.out.println("ECB解密成功》》》》："+new String(decrypted,"UTF-8"));
            return new String(decrypted, "UTF-8");
        }
        catch (Exception e)
        {
        	System.out.println("ECB解密失败，"+e.getMessage());
            //LOG.debug("ECB解密失败");
            return null;
        }
    }

    public String encryptData_CBC(String plainText,String secretKey)
    {
        try
        {
            Sm4Context ctx = new Sm4Context();
            ctx.isPadding = true;
            ctx.mode = Sm4.SM4_ENCRYPT;

            byte[] keyBytes;
            byte[] ivBytes;
            if (hexString)
            {
                keyBytes = Util.hexStringToBytes(secretKey);
                ivBytes = Util.hexStringToBytes(iv);
            }
            else
            {
                keyBytes = secretKey.getBytes();
                ivBytes = iv.getBytes();
            }

            Sm4 sm4 = new Sm4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes("UTF-8"));
            //String cipherText = new BASE64Encoder().encode(encrypted);
            String cipherText = Base64.encodeBase64String(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0)
            {
                Matcher m = P.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public String decryptData_CBC(String cipherText,String secretKey)
    {
        try
        {
            Sm4Context ctx = new Sm4Context();
            ctx.isPadding = true;
            ctx.mode = Sm4.SM4_DECRYPT;

            byte[] keyBytes;
            byte[] ivBytes;
            if (hexString)
            {
                keyBytes = Util.hexStringToBytes(secretKey);
                ivBytes = Util.hexStringToBytes(iv);
            }
            else
            {
                keyBytes = secretKey.getBytes();
                ivBytes = iv.getBytes();
            }

            Sm4 sm4 = new Sm4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            //byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
            byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Base64.decodeBase64(cipherText));
            return new String(decrypted, "UTF-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }



    /***
	 *
	 * @param encryptStr
	 * @return
	 */
	private static String decryptData(String encryptStr){
		System.out.println("decryptData start.=>"+encryptStr);
		Sm4Utils sm4Utils=new Sm4Utils();

		try{
			String decStr=sm4Utils.decryptData_ECB(encryptStr, "JLB6L6MJVIT5Z7IL");
			if(decStr!=null){
				System.out.println("decryptData decryptData_ECB successs."+decStr);
				return decStr;
			}
		}catch(Exception e){}

		try{
			String decStr=sm4Utils.decryptData_CBC(encryptStr, "JLB6L6MJVIT5Z7IL");
			if(decStr!=null){
				System.out.println("decryptData decryptData_CBC successs."+decStr);
			}
			return decStr;
		}catch(Exception e){
			return null;
		}
	}

    public static void main(String[] args) {
        Sm4Utils sm4Utils = new Sm4Utils();
        String password = "P@ssw0rd";
        String secretKey = "JLB6L6MJVIT5Z7IL";
        String enp = sm4Utils.encryptData_ECB("18438629268", secretKey);
        System.out.println("加密后为：" + enp);
        String Dec = sm4Utils.decryptData_ECB("Bh8m3ixejshmJ8GpjJnmpA==", secretKey);
        System.out.println("解密后：" + Dec);
    }

}
